package com.frontop.bigdata.aop;

import com.alibaba.fastjson.JSONObject;
import com.frontop.bigdata.config.NacosConfig;
import com.frontop.common.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
@Aspect//定义切面
public class LogAop {

        @Autowired
        NacosConfig nacosConfig;

        @Value("${spring.application.name}")
        private String moduleName;

        /**
         * @Pointcut：切点
         * @execution：连接点集合
         */
        @Pointcut(""
                + "execution(* com.frontop.bigdata.modules.controller..*(..))")
        private void logTransfer(){}


        /**
         * @Around：环绕通知
         */
        @Around("logTransfer()")
        public Object  controllerLog(ProceedingJoinPoint joinPoint) throws Throwable {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //开始时间
            long startTime = new Date().getTime();
            //响应结果
            Object result = joinPoint.proceed();
            //结束时间
            long endTime = new Date().getTime();
            //是否开启日志记录
            if (nacosConfig.isOpenLog()) {
                JSONObject logJson = new JSONObject();
                //模块
                logJson.put("moduleName",moduleName);
                //ip
                logJson.put("ip", LogUtil.getRemoteHost(request));
                //请求参数
                logJson.put("param",LogUtil.postHandle(LogUtil.filterParamList(joinPoint)));
                //响应参数
                logJson.put("result",LogUtil.postHandle(result));
                //类和方法名称
                logJson.put("methodName",joinPoint.getTarget().getClass().getSimpleName() + "." + joinPoint.getSignature().getName());
                //耗时
                logJson.put("elapsedTime",endTime - startTime);
                //用户
                logJson.put("userName",request.getRemoteUser());
                log.info(logJson.toJSONString());
            }
            return result;
        }
}
